package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.TemplateShare;
import com.micro.ai.template.service.TemplateShareService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 模板分享Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/template/shares")
@RequiredArgsConstructor
@Tag(name = "模板分享管理", description = "模板分享相关接口")
public class TemplateShareController {

    private final TemplateShareService templateShareService;

    @PostMapping
    @PreAuthorize("hasAuthority('template:share:create')")
    @Operation(summary = "创建分享", description = "创建模板分享链接")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功",
            content = @Content(schema = @Schema(implementation = TemplateShare.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<TemplateShare> createShare(
            @Valid @RequestBody TemplateShare templateShare,
            Authentication authentication) {
        String userId = authentication.getName();
        templateShare.setUserId(userId);
        
        log.info("创建分享请求, templateId: {}, userId: {}", templateShare.getTemplateId(), userId);
        return ApiResponse.success(templateShareService.createShare(templateShare));
    }

    @GetMapping("/code/{shareCode}")
    @Operation(summary = "通过分享码获取", description = "通过分享码获取分享信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = TemplateShare.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "分享不存在或已过期"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "分享已达访问上限")
    })
    public ApiResponse<TemplateShare> getShareByCode(
            @Parameter(description = "分享码") @PathVariable String shareCode) {
        TemplateShare share = templateShareService.getShareByCode(shareCode);
        
        // 增加访问次数
        templateShareService.incrementAccessCount(share.getId());
        
        return ApiResponse.success(share);
    }

    @DeleteMapping("/{shareId}")
    @PreAuthorize("hasAuthority('template:share:delete')")
    @Operation(summary = "撤销分享", description = "撤销分享链接")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "撤销成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "分享不存在")
    })
    public ApiResponse<Void> revokeShare(
            @Parameter(description = "分享ID") @PathVariable String shareId,
            Authentication authentication) {
        String userId = authentication.getName();
        log.info("撤销分享请求, shareId: {}, userId: {}", shareId, userId);
        templateShareService.revokeShare(shareId, userId);
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/user")
    @PreAuthorize("hasAuthority('template:share:query')")
    @Operation(summary = "查询用户分享列表", description = "分页查询当前用户的分享列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<IPage<TemplateShare>> getUserShares(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size,
            Authentication authentication) {
        String userId = authentication.getName();
        Page<TemplateShare> page = new Page<>(current, size);
        return ApiResponse.success(templateShareService.getUserShares(userId, page));
    }

    @GetMapping("/check/{shareCode}")
    @Operation(summary = "检查分享有效性", description = "检查分享码是否有效")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "分享码不存在")
    })
    public ApiResponse<Map<String, Boolean>> checkShareValid(
            @Parameter(description = "分享码") @PathVariable String shareCode) {
        boolean valid = templateShareService.isShareValid(shareCode);
        
        Map<String, Boolean> result = new HashMap<>();
        result.put("valid", valid);
        
        return ApiResponse.success(result);
    }
}

